package impl

import (
	"github.com/gin-gonic/gin"
	"github.com/spf13/cast"
	"github.com/starmotioncf/common/filter"
	"github.com/starmotioncf/soutchatinternal"
	"github.com/starmotioncf/soutchatinternal/repository"
	"sync"
)

// filter 相关的信息，懒加载对象
type lazyFilterEntity struct {
	ctx      *gin.Context
	mux      *sync.Mutex
	data     filter.EntityData
	uid      uint64
	userRepo repository.UserRepository
}

func newEntityLazyByCtx(ctx *gin.Context, data filter.EntityData, userRepo repository.UserRepository) filter.Entity {
	_data := make(filter.EntityData)
	tp := internal.GetTokenPayloadCtx(ctx)
	if tp != nil {
		_data[filter.UID] = tp.Uid
		_data[filter.Region] = tp.Region
	}
	if data != nil {
		for k, v := range data {
			_data[k] = v
		}
	}
	return &lazyFilterEntity{
		ctx:      ctx,
		mux:      &sync.Mutex{},
		data:     _data,
		userRepo: userRepo,
	}
}

func (ei *lazyFilterEntity) GetValue(et filter.EntityT) any {
	ei.mux.Lock()
	defer ei.mux.Unlock()
	if v, ok := ei.data[et]; ok {
		return v
	}
	ei.setupUserInfo(et)
	return ei.data[et]
}

func (ei *lazyFilterEntity) setupUserInfo(et filter.EntityT) {
	uid := cast.ToUint64(ei.data[filter.UID])
	// 下面都是根据uid查数据的， 为0的话，也不需要查了
	if uid == 0 {
		return
	}
	//switch et {
	//case filter_v2.Region:
	//	ei.data[filter_v2.Region] = ei.userRepo.GetRegion(ei.ctx, uid) //分区
	//case filter_v2.Country, filter_v2.Wealth, filter_v2.Charm:
	//	userBase, err := ei.userRepo.GetBaseCache(ei.ctx, uid)
	//	if err != nil {
	//		logs.Error("setupInfo userRepo.GetBaseInfo error", uid, err)
	//		return
	//	}
	//	if userBase == nil {
	//		return
	//	}
	//	ei.data[filter_v2.Country] = userBase.CountryId //国家id
	//	ei.data[filter_v2.Wealth] = userBase.WealthLv   //财富等级
	//	ei.data[filter_v2.Charm] = userBase.CharmLv     //魅力等级
	//case filter_v2.President, filter_v2.Anchor:
	//	guildInfo, err := ei.guildRepo.GetUserGuild(ei.ctx, uid)
	//	if err != nil {
	//		if !errors.Is(err, gorm.ErrRecordNotFound) {
	//			logs.Error("setupInfo guildRepo.GetUserGuild error", uid, err)
	//		}
	//	}
	//	president := 0
	//	anchor := 0
	//	if guildInfo != nil {
	//		anchor = 1
	//		if guildInfo.AdminUid == guildInfo.Uid {
	//			president = 1
	//		}
	//	}
	//	ei.data[filter_v2.President] = president //是否公会长
	//	ei.data[filter_v2.Anchor] = anchor       //是否主播
	//case filter_v2.Recharge:
	//	total, err := ei.orderRepo.GetPayPurchasedTotalWithAgent(ei.ctx, uid)
	//	if err != nil {
	//		logs.Error("setupInfo orderRepo.GetPayPurchasedTotalWithAgent error", uid, err)
	//	}
	//	ei.data[filter_v2.Recharge] = total //充值总金额
	//}
}
